package org.umss.fixturebuilder.builder;

import java.util.List;
import org.umss.fixturebuilder.builder.model.Game;
import org.umss.fixturebuilder.builder.model.Phase;
import org.umss.fixturebuilder.builder.model.Round;
import org.umss.fixturebuilder.builder.model.Team;
import org.umss.fixturebuilder.model.appengine.PhaseType;

/**
 *
 * @author Daniela Meneses
 */
public class GroupPhaseBuilder implements PhaseBuilder {

    private final int teamPerGroup;
    private static final String NOT_VALID_TEAMS_NUMBER = "The number of teams is not valid to build a group phase.";
    private static final String NOT_VALID_TEAMS_PER_GROUP = "The number of teams per group is invalid.";

    public GroupPhaseBuilder(int teamPerGroup) throws PhaseBuilderException {
        if(teamPerGroup <= 0) {
            throw new PhaseBuilderException(NOT_VALID_TEAMS_PER_GROUP);
        }
        this.teamPerGroup = teamPerGroup;
    }

    public Phase generatePhase(List<Team> teams) throws PhaseBuilderException {
        int teamsCount = teams.size();
        
        if (teamsCount % teamPerGroup != 0) {
            throw new PhaseBuilderException(NOT_VALID_TEAMS_NUMBER);
        }

        Phase phase = new Phase(PhaseType.GROUPS);
        int rountCount = teamsCount / teamPerGroup;
        for (int i = 0; i < rountCount; i++) {
            phase.addRound(buildRound(teams, i));
        }
        return phase;
    }

    public Round buildRound(List<Team> teams, int roundNumber) {
        List<Team> subList = teams.subList(roundNumber * teamPerGroup, roundNumber * teamPerGroup + teamPerGroup);
        AllAgainstAllPhaseBuilder allPhaseBuilder = new AllAgainstAllPhaseBuilder();
        Phase generatedPhase = allPhaseBuilder.generatePhase(subList);
        List<Round> rounds = generatedPhase.getRounds();
        Round result = new Round();
        for (Round round : rounds) {
            List<Game> games = round.getGames();
            for (Game game : games) {
                result.addGame(game);
            }
        }
        return result;
    }
}
